package com.heima.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.heima.feign.ArticleFeignClient;
import com.heima.feign.WemediaFeignClient;
import com.heima.model.article.pojos.Article;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.Comment;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.constants.AliyunConstants;
import com.heima.service.CommentService;
import com.heima.utils.common.AliyunDetect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author chenshan
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private WemediaFeignClient wemediaFeignClient;

    @Autowired
    private ArticleFeignClient articleFeignClient;

    /**
     * 保存评论
     *
     * @param saveDto 用户评论信息
     * @return ResponseResult
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto saveDto) throws Exception {
        // 校验参数的合法性
        if (!ObjectUtil.isAllNotEmpty(saveDto.getArticleId(), StrUtil.trim(saveDto.getContent()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 对用户评论的内容进行违规检测
        // 1.先进行本地自定义敏感词校验（DFA校验）
        Boolean checkContent = false;
        ResponseResult<Boolean> result = wemediaFeignClient.checkContent(saveDto.getContent());
        if (ObjectUtil.isNotEmpty(result)) {
            checkContent = result.getData();
        }

        // 2.使用第三方文本违规检测SDK进行校验
        String aliyunCheckContent = AliyunDetect.checkContent(saveDto.getContent());

        // 用户评论内容违规
        if (checkContent || !StrUtil.equals(AliyunConstants.ALIYUN_DETECT_PASS, aliyunCheckContent, true)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容涉及敏感信息~");
        }

        // 用户评论内容审核通过 准备评论信息
        Comment comment = new Comment();

        Article article = articleFeignClient.findArticleById(saveDto.getArticleId());
        if (ObjectUtil.isNull(article)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        comment.setAuthorId(article.getAuthorId());
        comment.setAuthorName(article.getAuthorName());
        comment.setEntryId(article.getId());
        comment.setContent(saveDto.getContent());
        comment.setType(0);
        comment.setLikes(0);
        comment.setReply(0);
        comment.setFlag(0);
        comment.setCreatedTime(DateTime.now());

        // 将用户评论信息保存到MongoDB中
        mongoTemplate.insert(comment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
